﻿
using System;
using System.Runtime.InteropServices;
using System.Management;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Win32;

#region how use this?
/*
string sVol = getvol.GetVolOf("C");
*/
#endregion

public class GetRegString
{

    [DllImport("kernel32.dll")]
    private static extern int GetVolumeInformation(
    string lpRootPathName,
    string lpVolumeNameBuffer,
    int nVolumeNameSize,
    ref int lpVolumeSerialNumber,
    int lpMaximumComponentLength,
    int lpFileSystemFlags,
    string lpFileSystemNameBuffer,
    int nFileSystemNameSize
    );

    public static string GetVolOf(string drvID)
    {
        try
        {
            const int MAX_FILENAME_LEN = 256;
            int retVal = 0;
            int a = 0;
            int b = 0;
            string str1 = null;
            string str2 = null;


            int i = GetVolumeInformation(
            drvID + @":\",
            str1,
            MAX_FILENAME_LEN,
            ref retVal,
            a,
            b,
            str2,
            MAX_FILENAME_LEN
            );

            return retVal.ToString("x");
        }
        catch { return string.Empty; }
    }


    public static string GetInfo()
    {
        try
        {
            string cpuInfo = "";//cpu序列号 
            ManagementClass cimobject = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                return cpuInfo.ToString();
            }

            return string.Empty;
        }
        catch { return string.Empty; }
    }

    public bool IsReged(string MachString)
    {
        string regFilePath = Application.StartupPath + "resource.wds";
        if (File.Exists(regFilePath))
        {
            return false;
        }
        FileStream fs = File.Open(regFilePath, FileMode.Open);
        string regKey = fs.ToString().Trim();

        ClassJiami jiami = new ClassJiami();
        string matchKey = jiami.Encrypto(GetVolOf(GetInfo()));
        if (matchKey != regKey)
        {
            return false;
        }
        return true;
    }
}

/// <summary> 
/// 对称加密算法类 
/// </summary> 
public class ClassJiami
{

    private SymmetricAlgorithm mobjCryptoService;
    private string Key;
    /// <summary> 
    /// 对称加密类的构造函数 
    /// </summary> 
    public ClassJiami()
    {
        mobjCryptoService = new RijndaelManaged();
        Key = "35,10,53,98,76,54,32,10,aa,dc,75,82,14,88,96,87";// "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
    }
    /// <summary> 
    /// 获得密钥 
    /// </summary> 
    /// <returns>密钥</returns> 
    private byte[] GetLegalKey()
    {
        string sTemp = Key;
        mobjCryptoService.GenerateKey();
        byte[] bytTemp = mobjCryptoService.Key;
        int KeyLength = bytTemp.Length;
        if (sTemp.Length > KeyLength)
            sTemp = sTemp.Substring(0, KeyLength);
        else if (sTemp.Length < KeyLength)
            sTemp = sTemp.PadRight(KeyLength, ' ');
        return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }
    /// <summary> 
    /// 获得初始向量IV 
    /// </summary> 
    /// <returns>初试向量IV</returns> 
    private byte[] GetLegalIV()
    {
        string sTemp = "22,10,53,98,76,54,32,10";//"wofslkdfjlsjdforeirwj*39323232403584";

        mobjCryptoService.GenerateIV();
        byte[] bytTemp = mobjCryptoService.IV;
        int IVLength = bytTemp.Length;
        if (sTemp.Length > IVLength)
            sTemp = sTemp.Substring(0, IVLength);
        else if (sTemp.Length < IVLength)
            sTemp = sTemp.PadRight(IVLength, ' ');
        return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }
    /// <summary> 
    /// 加密方法 
    /// </summary> 
    /// <param name=Source>待加密的串</param> 
    /// <returns>经过加密的串</returns> 
    public string Encrypto(string Source)
    {
        byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
        MemoryStream ms = new MemoryStream();
        mobjCryptoService.Key = GetLegalKey();
        mobjCryptoService.IV = GetLegalIV();
        ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
        CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
        cs.Write(bytIn, 0, bytIn.Length);
        cs.FlushFinalBlock();
        ms.Close();
        byte[] bytOut = ms.ToArray();
        return Convert.ToBase64String(bytOut);
    }
    /// <summary> 
    /// 加密数组 
    /// </summary> 
    /// <param name=Source>待加密的数组</param> 
    /// <returns>经过加密的数组</returns> 
    public byte[] EncryptoByte(byte[] bytIn)
    {
        MemoryStream ms = new MemoryStream();
        mobjCryptoService.Key = GetLegalKey();
        mobjCryptoService.IV = GetLegalIV();
        ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
        CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
        cs.Write(bytIn, 0, bytIn.Length);
        cs.FlushFinalBlock();
        ms.Close();
        byte[] bytOut = ms.ToArray();
        return bytOut;
    }
    /// <summary> 
    /// 解密方法 
    /// </summary> 
    /// <param name=Source>待解密的串</param> 
    /// <returns>经过解密的串</returns> 
    public string Decrypto(string Source)
    {
        byte[] bytIn;
        bytIn = Convert.FromBase64String(Source);
        MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
        mobjCryptoService.Key = GetLegalKey();
        mobjCryptoService.IV = GetLegalIV();
        ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
        CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
        StreamReader sr = new StreamReader(cs);
        return sr.ReadToEnd();
    }

    /// <summary> 
    /// 解密数组 
    /// </summary> 
    /// <param name=Source>待解密的数组</param> 
    /// <returns>经过解密的数组</returns> 
    public byte[] DecryptoByte(byte[] bytIn)
    {
        byte[] writeData = new byte[4096];
        MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
        mobjCryptoService.Key = GetLegalKey();
        mobjCryptoService.IV = GetLegalIV();
        //mobjCryptoService.BlockSize = 256;
        ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
        Stream s2 = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
        MemoryStream outStream = new MemoryStream();
        while (true)
        {
            int size = s2.Read(writeData, 0, writeData.Length);
            if (size > 0)
            {
                outStream.Write(writeData, 0, size);
            }
            else
            {
                break;
            }
        }
        s2.Close();
        byte[] outArr = outStream.ToArray();
        outStream.Close();
        return outArr;
    }
}

/// <summary>
/// Rijndael
/// </summary>
public class Rijndael_
{
    private RijndaelManaged myRijndael;
    public string Key;
    public string IV;
    /// <summary>
    /// 对称加密类的构造函数
    /// </summary>
    public Rijndael_(string key)
    {
        myRijndael = new RijndaelManaged();
        Key = key;
        IV = "67^%*(&(*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
    }
    /// <summary>
    /// 对称加密类的构造函数
    /// </summary>
    public Rijndael_(string key, string iv)
    {
        myRijndael = new RijndaelManaged();
        Key = key;
        IV = iv;
    }
    /// <summary>
    /// 获得密钥
    /// </summary>
    /// <returns>密钥</returns>
    private byte[] GetLegalKey()
    {
        string sTemp = Key;
        myRijndael.GenerateKey();
        byte[] bytTemp = myRijndael.Key;
        int KeyLength = bytTemp.Length;
        if (sTemp.Length > KeyLength)
            sTemp = sTemp.Substring(0, KeyLength);
        else if (sTemp.Length < KeyLength)
            sTemp = sTemp.PadRight(KeyLength, ' ');
        return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }
    /// <summary>
    /// 获得初始向量IV
    /// </summary>
    /// <returns>初试向量IV</returns>
    private byte[] GetLegalIV()
    {
        string sTemp = IV;
        myRijndael.GenerateIV();
        byte[] bytTemp = myRijndael.IV;
        int IVLength = bytTemp.Length;
        if (sTemp.Length > IVLength)
            sTemp = sTemp.Substring(0, IVLength);
        else if (sTemp.Length < IVLength)
            sTemp = sTemp.PadRight(IVLength, ' ');
        return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }
    /// <summary>
    /// 加密方法
    /// </summary>
    /// <param name="Source">待加密的串</param>
    /// <returns>经过加密的串</returns>
    public string Encrypt(string Source)
    {
        try
        {
            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
            MemoryStream ms = new MemoryStream();
            myRijndael.Key = GetLegalKey();
            myRijndael.IV = GetLegalIV();
            ICryptoTransform encrypto = myRijndael.CreateEncryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            ms.Close();
            byte[] bytOut = ms.ToArray();
            return Convert.ToBase64String(bytOut);
        }
        catch (Exception ex)
        {
            throw new Exception("在文件加密的时候出现错误！错误提示： \n" + ex.Message);
        }
    }
    /// <summary>
    /// 解密方法
    /// </summary>
    /// <param name="Source">待解密的串</param>
    /// <returns>经过解密的串</returns>
    public string Decrypt(string Source)
    {
        try
        {
            byte[] bytIn = Convert.FromBase64String(Source);
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            myRijndael.Key = GetLegalKey();
            myRijndael.IV = GetLegalIV();
            ICryptoTransform encrypto = myRijndael.CreateDecryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }
        catch (Exception ex)
        {
            throw new Exception("在文件解密的时候出现错误！错误提示： \n" + ex.Message);
        }
    }
    /// <summary>
    /// 加密方法byte[] to byte[]
    /// </summary>
    /// <param name="Source">待加密的byte数组</param>
    /// <returns>经过加密的byte数组</returns>
    public byte[] Encrypt(byte[] Source)
    {
        try
        {
            byte[] bytIn = Source;
            MemoryStream ms = new MemoryStream();
            myRijndael.Key = GetLegalKey();
            myRijndael.IV = GetLegalIV();
            ICryptoTransform encrypto = myRijndael.CreateEncryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            ms.Close();
            byte[] bytOut = ms.ToArray();
            return bytOut;
        }
        catch (Exception ex)
        {
            throw new Exception("在文件加密的时候出现错误！错误提示： \n" + ex.Message);
        }
    }
    /// <summary>
    /// 解密方法byte[] to byte[]
    /// </summary>
    /// <param name="Source">待解密的byte数组</param>
    /// <returns>经过解密的byte数组</returns>
    public byte[] Decrypt(byte[] Source)
    {
        try
        {
            byte[] bytIn = Source;
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            myRijndael.Key = GetLegalKey();
            myRijndael.IV = GetLegalIV();
            ICryptoTransform encrypto = myRijndael.CreateDecryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return UTF8Encoding.UTF8.GetBytes(sr.ReadToEnd());
        }
        catch (Exception ex)
        {
            throw new Exception("在文件解密的时候出现错误！错误提示： \n" + ex.Message);
        }
    }


    /// <summary>
    /// 加密方法File to File
    /// </summary>
    /// <param name="inFileName">待加密文件的路径</param>
    /// <param name="outFileName">待加密后文件的输出路径</param>

    public void Encrypt(string inFileName, string outFileName)
    {
        try
        {
            //byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
            //MemoryStream ms = new MemoryStream();

            FileStream fin = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            myRijndael.Key = GetLegalKey();
            myRijndael.IV = GetLegalIV();

            byte[] bin = new byte[100];
            long rdlen = 0;
            long totlen = fin.Length;
            int len;

            ICryptoTransform encrypto = myRijndael.CreateEncryptor();
            CryptoStream cs = new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                cs.Write(bin, 0, len);
                rdlen = rdlen + len;
            }
            cs.Close();
            fout.Close();
            fin.Close();

        }
        catch (Exception ex)
        {
            throw new Exception("在文件加密的时候出现错误！错误提示： \n" + ex.Message);
        }
    }
    /// <summary>
    /// 解密方法File to File
    /// </summary>
    /// <param name="inFileName">待解密文件的路径</param>
    /// <param name="outFileName">待解密后文件的输出路径</param>
    public void Decrypt(string inFileName, string outFileName)
    {
        try
        {
            FileStream fin = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            byte[] bin = new byte[100];
            long rdlen = 0;
            long totlen = fin.Length;
            int len;
            myRijndael.Key = GetLegalKey();
            myRijndael.IV = GetLegalIV();
            ICryptoTransform encrypto = myRijndael.CreateDecryptor();
            CryptoStream cs = new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                cs.Write(bin, 0, len);
                rdlen = rdlen + len;
            }
            cs.Close();
            fout.Close();
            fin.Close();

        }
        catch (Exception ex)
        {
            throw new Exception("在文件解密的时候出现错误！错误提示： \n" + ex.Message);
        }
    }
}

    public class RegistryKey_Operate
    {
        string CompanyInfo;
        public RegistryKey_Operate(string Path)
        {
            CompanyInfo = Path;
        }
        /// <summary>
        /// 读取注册表的键值
        /// </summary>
        /// <param name="name">需要读取的键值名</param>
        /// <returns></returns>
        public string GetRegistData(string name)
        {
            string registData;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.OpenSubKey(CompanyInfo, true);
            registData = aimdir.GetValue(name).ToString();
            return registData;
        }

        /// <summary>
        /// 向注册表中写数据
        /// </summary>
        /// <param name="name">键名</param>
        /// <param name="tovalue">键值</param>
        public void WTRegedit(string name, string tovalue)
        {
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey software = hklm.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.CreateSubKey(CompanyInfo);
            aimdir.SetValue(name, tovalue);
        }

        /// <summary>
        /// 删除注册表中指定的注册表项
        /// </summary>
        /// <param name="name">键名</param>
        public void DeleteRegist(string name)
        {
            string[] aimnames;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.OpenSubKey(CompanyInfo, true);
            aimnames = aimdir.GetSubKeyNames();
            foreach (string aimKey in aimnames)
            {
                if (aimKey == name)
                    aimdir.DeleteSubKeyTree(name);
            }
        }

        /// <summary>
        /// 判断指定注册表项是否存在
        /// </summary>
        /// <param name="name">键名</param>
        /// <returns></returns>
        public bool IsRegeditExit(string name)
        {
            bool _exit = false;
            bool exit = false;
            string[] subkeyNames;
            string[] subkeys;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
            subkeys = software.GetSubKeyNames();
            foreach (string keyname in subkeys)
            {
                if (keyname == CompanyInfo)
                {
                    exit = true;
                    break;
                }
            }
            if (!exit)
            {
                return exit;
            }
            else
            {
                RegistryKey aimdir = software.OpenSubKey(CompanyInfo, true);
                subkeyNames = aimdir.GetValueNames();
                foreach (string keyName in subkeyNames)
                {
                    if (keyName == name)
                    {
                        _exit = true;
                        return _exit;
                    }
                }
            }
            return _exit;
        }
    }




